package com.kele.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author kele
 * @date 2021/10/12 16:58
 * @description
 * futureTask 异步调用
 */
public class FutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * 没有返回值的异步调用
         */
//        CompletableFuture<Void> completableFuture=CompletableFuture.runAsync(()->{
//            try {
//                TimeUnit.SECONDS.sleep(2);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(Thread.currentThread().getName()+"runAsync()=>Void");
//        });
//        System.out.println(1111);
//
//        completableFuture.get();


        /**
         * 有返回值的 异步回调
         */
        CompletableFuture<Integer> completableFuture1=CompletableFuture.supplyAsync(()->{
            System.out.println(Thread.currentThread().getName()+"runAsync()=>Integer");
            int i=1/0;
            return 1024;
        });

        completableFuture1.whenComplete((t,u)->{
            /**
             * 正常返回结果
             */
            System.out.println("t=>"+t);
            /**
             * 可以获取到错误的返回结果
             */
            System.out.println("u=>"+u);
        }).exceptionally((e)->{
            e.getMessage();
            return 233;
        }).get();

    }
}
